#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2020-08-27 16:02:25
# @Author  : Zuo Zhongfei (zuozhongfei@126.com)
# @Link    : www
# @Version : $Id$

import os
import json

# username = input("What is you name?")
# filename = 'username.json'

# with open(filename, 'w') as file_object:
#     json.dump(username, file_object)
#     print("I'll remeber you when you come back," + username + "!")


# 下面是加强版，将输入名字，和读取名字放到一个地方
# 如果之前存储了用户名，就加载他
# 否则，就提示用户输入用户名并存储他
# filename = 'username.json'
# try:
#     with open(filename) as file_object:
#         username = json.load(file_object)
# except FileNotFoundError as e:
#     username = input("你叫什么名字：：")
#     with open(filename, 'w') as file_object:
#         json.dump(username, file_object)
#         print("我记住你了：" + username + "!")
# else:
#     print("欢迎回来：" + username)

# 重构上边的程序，使用函数封装各个部分
# def greet_user():
#     """问候用户，并指出其名字"""
#     filename = "username.json"
#     try:
#         with open(filename) as file_object:
#             username = json.load(file_object)
#     except FileNotFoundError as e:
#         username = input("你叫什么名字：：")
#         with open(filename, 'w') as file_object:
#             json.dump(username, file_object)
#             print("我记住你了：" + username + "!")
#     else:
#         print("欢迎回来：" + username)


# 再次重构，将读取用户名和写入用户名分开
def get_stored_username():
    """获取本地存储的用户名"""
    filename = "username.json"
    try:
        with open(filename) as file_object:
            username = json.load(file_object)
    except Exception as e:
        return None
    else:
        return username


def get_new_username():
    """提示用户输入用户名"""
    username = input("你叫什么名字：")
    filename = 'username.json'
    with open(filename, 'w') as file_object:
        json.dump(username, file_object)
        print("我记住你了：" + username + "!")
    return username


def greet_user():
    """问候用户，并指出其名字"""
    username = get_stored_username()
    if username:
        print("欢迎回来：" + username)
    else:
        username = get_new_username()


greet_user()